import sha

from myelin.Ns import MYELINS
from nodetypes.formats.mml.Events import EventHandler

from myelin.server.lib.http import ParamValidators
from myelin.server.lib.http import Status

from forms import Commit

class ParamsFetcher(object):
    
    maxNickLen = 128
    maxPasswdLen = 32
    
    def fetchParams(self, context, source, params, errors):        
        defaults = context.defaults
        args = context.request.args
        
        params['nick'] = ParamValidators.SingleString(
            'nick',
            args,
            errors,
            min=1,
            max=getattr(defaults,'agent_nick_length',None)
        )
        
        params['passwd'] = ParamValidators.SingleString(
            'passwd',
            args,
            errors,
            min=1,
            max = getattr(defaults,'agent_password_length',None)
        )
        
        params['session-ttl'] = ParamValidators.NumberRange(
            'session-ttl',
            args,
            errors,
            min=int(defaults.session_ttl),
            max=int(defaults.max_session_ttl),
            default=int(defaults.session_ttl)
        )
        
        domains = context.account.domains
        if len(domains) > 1:
            params['domain'] = ParamValidators.SelectOption(
                'domain',
                args,
                errors,
                domains
            )
        else:
            params['domain'] = domains.keys()[0]
        
        return params, errors


class EventHandler(EventHandler):
    
    newCommitForm      = Commit.Form
    newParamsFetcher   = ParamsFetcher
    
    def process(self, context, source):
        
        params, errors = self.newParamsFetcher().fetchParams(
            context,
            source,
            {}, {}
        )
        
        eventData = context.event.data
        if not errors and context.session.login(
            params['domain'],
            params['nick'],
            sha.new(params['passwd']).hexdigest(),
            params['session-ttl']
        ):
            eventData.status = u'success'
            eventData.status_type = u'login-success'
            context.request.args['nick'] = [str(params['nick']),]
            return self.newRedirectDocument().createDocument(context, source) 
        
        eventData.status = u'failure'
        eventData.status_type = u'login-failure'
        eventData.params = params
        eventData.errors = errors
        
        eventData.form = self.newCommitForm()
        eventData.stage = 0
        eventData.submits = context.transform.submitEvents[0]
        
        context.model = context.nodeType.retrieveModel(context) 
        context.request.status = Status.BAD_REQUEST
        return self.newDocument().createDocument(context, source)